package com.project.utils;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.experimental.UtilityClass;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yanxinqing
 */
@UtilityClass
public class ObjectUtils {

    private void copyProperties(Object src, Object target) {
        BeanUtils.copyProperties(src, target);
    }

    public <Src, Target> Target convert(Src src, Class<Target> clazz) {
        if (src == null || clazz == null) {
            return null;
        }

        try {
            Target result = clazz.getDeclaredConstructor().newInstance();
            copyProperties(src, result);
            return result;
        } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException | InstantiationException e) {
            e.printStackTrace();
        }

        return null;
    }

    public <Src, Target> List<Target> convert(List<Src> src, Class<Target> clazz) {
        if (src == null || clazz == null) {
            return null;
        }

        return src.stream()
                .map(c -> convert(c, clazz))
                .collect(Collectors.toList());
    }

    public <Src, Target> IPage<Target> convert(IPage<Src> src, Class<Target> clazz) {
        if (src == null || clazz == null) {
            return null;
        }

        return src.convert(c -> convert(c, clazz));
    }

}
